﻿Imports System.IO
Imports ATS.UI.Process.ATSLOCALServiceReference
Imports ATS.UI.Process.ATSLOCALAUTHENTICATIONServiceReference
Imports System.ServiceModel
Imports System.Configuration
Imports System.Web
Imports System.Web.Configuration
Imports System.ServiceModel.Channels
Imports System.Net
Imports OpenNETCF.Desktop.Communication
Imports System.ComponentModel


Class MainWindow
    Dim FileFound As Integer
    Dim SearchCriteria As String = My.Settings.SearchCriteria
    Dim oRapi As RAPI
    Dim localLocation As String = My.Settings.localLocation
    Dim remoteLocation As String = My.Settings.remoteLocation
    Dim retainFilesonReader As Boolean = My.Settings.retainFilesonReader
    Dim successRecordCtr As Integer = 0
    Dim duplicateRecordCtr As Integer = 0
    Dim noRecordRecordCtr As Integer = 0
    Dim remotefileCount As Integer = 0
    Private WithEvents _backgroundWorker As BackgroundWorker
    Dim path As String = localLocation
    Dim CriteriaPath, files, filename As String
    Dim auth As New ATS.UI.Process.ATSLOCALAUTHENTICATIONServiceReference.AuthenticationServiceSoapClient
    Dim dataService As New ATS.UI.Process.ATSLOCALServiceReference.jokoatsDataDomainServiceSoapClient
    Dim request As New HttpRequestMessageProperty()
    Dim duplicatesCtr As Integer = 0
    Dim notRelatedToAnyAsset As Integer = 0
    Dim fileCtr As Integer = 0

    Private Sub _backgroundWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles _backgroundWorker.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        processFiles()
    End Sub

    Private Sub _backgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles _backgroundWorker.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            LabelNoAsset.Content = notRelatedToAnyAsset
            LabelDuplicates.Content = duplicatesCtr
            LabelNumberofFilesProcessed.Content = fileCtr
        End If
        busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Collapsed
    End Sub


    Sub LoadReaderData()
        Dim sharedCookie As String = String.Empty
        Dim auth As New ATS.UI.Process.ATSLOCALAUTHENTICATIONServiceReference.AuthenticationServiceSoapClient
        Dim dataService As New ATS.UI.Process.ATSLOCALServiceReference.jokoatsDataDomainServiceSoapClient

        Using New OperationContextScope(auth.InnerChannel)
            Dim result = auth.Login("admin", "joko123!", True, "").RootResults.FirstOrDefault()

            ' Extract the cookie embedded in the received web service response
            ' and stores it locally
            Dim response As HttpResponseMessageProperty = DirectCast(OperationContext.Current.IncomingMessageProperties(HttpResponseMessageProperty.Name), HttpResponseMessageProperty)
            sharedCookie = response.Headers("Set-Cookie")
        End Using

        oRapi = New RAPI



        Using New OperationContextScope(dataService.InnerChannel)
            ' Embeds the extracted cookie in the next web service request
            ' Note that we manually have to create the request object since
            ' since it doesn't exist yet at this stage 
            Dim request As New HttpRequestMessageProperty()
            request.Headers("Cookie") = sharedCookie
            OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = request

            Dim newScan As New ATS.UI.Process.ATSLOCALServiceReference.RFIDScanHistory
            With newScan
                .RFIDNum = "123"
                .DateScanned = Now
            End With

            Dim csEntry As UI.Process.ATSLOCALServiceReference.ChangeSetEntry = New UI.Process.ATSLOCALServiceReference.ChangeSetEntry()
            With csEntry
                .Operation = UI.Process.ATSLOCALServiceReference.DomainOperation.Insert
                .Entity = newScan
            End With

            dataService.SubmitChanges(New List(Of UI.Process.ATSLOCALServiceReference.ChangeSetEntry)() From {csEntry})




        End Using


        Using New OperationContextScope(dataService.InnerChannel)
            ' Embeds the extracted cookie in the next web service request
            ' Note that we manually have to create the request object since
            ' since it doesn't exist yet at this stage 
            Dim request As New HttpRequestMessageProperty()
            request.Headers("Cookie") = sharedCookie
            OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = request

            Dim asset = dataService.AssetByRFIDNo("", 123)
            Dim mAssetorig As New UI.Process.ATSLOCALServiceReference.MainAssetsTable
            With asset.RootResults.FirstOrDefault
                mAssetorig.AssetAmount = .AssetAmount
                mAssetorig.Assetno = .Assetno
                mAssetorig.AssignToEmployeeCode = .AssignToEmployeeCode
                mAssetorig.BaseCost = .BaseCost
                mAssetorig.BoughtFrom = .BoughtFrom
                mAssetorig.BrandName = .BrandName
                mAssetorig.CategoryCode = .CategoryCode
                mAssetorig.Condition = .Condition
                mAssetorig.Createdby = .Createdby
                mAssetorig.DateAcquired = .DateAcquired
                mAssetorig.DateCreated = .DateCreated
                mAssetorig.DeptCode = .DeptCode
                mAssetorig.DescriptiveName = .DescriptiveName
                mAssetorig.EstimatedValue = .EstimatedValue
                mAssetorig.InvoiceNumber = .InvoiceNumber
                mAssetorig.LastModified = .LastModified
                mAssetorig.LastModifiedBy = .LastModifiedBy
                mAssetorig.LastScanDate = .LastScanDate
                mAssetorig.LocationCode = .LocationCode
                mAssetorig.Manufacturer = .Manufacturer
                mAssetorig.ModelNumber = .ModelNumber
                mAssetorig.Remarks = .Remarks
                mAssetorig.ReplacementCost = .ReplacementCost
                mAssetorig.RFIDno = .RFIDno
                mAssetorig.SalvageValue = .SalvageValue
                mAssetorig.Section = .Section
                mAssetorig.SerialNumber = .SerialNumber
                mAssetorig.Status = .Status
                mAssetorig.VAT = .VAT
            End With
            'mAssetorig.id = asset.RootResults.FirstOrDefault.id
            'mAssetorig.c_property = asset.RootResults.FirstOrDefault.c_property
            'mAssetorig.value = asset.RootResults.FirstOrDefault.value
            asset.RootResults.FirstOrDefault.VAT = 4

            Dim csEntry As New UI.Process.ATSLOCALServiceReference.ChangeSetEntry
            With csEntry
                .Operation = UI.Process.ATSLOCALServiceReference.DomainOperation.Update
                .OriginalEntity = mAssetorig
                .Entity = asset.RootResults.FirstOrDefault
            End With


            dataService.SubmitChanges(New List(Of UI.Process.ATSLOCALServiceReference.ChangeSetEntry)() From {csEntry})




            '' Retrieve the full collection,   
            '' no ability to filter server side unless additional methods exposed  
            'Dim result As QueryResultOfMainAssetsTable = dataService.MainAssetsTables_All("")
            'Dim tasks As List(Of MainAssetsTable) = result.RootResults
            'tasks(0).LastModifiedBy = "me"
            '' Wrap it in ChangeSetEntry  
            'Dim changeEntry As New UI.Process.ATSDataDomainServiceReference.ChangeSetEntry()
            'changeEntry.Entity = tasks(0)
            'changeEntry.Operation = UI.Process.ATSDataDomainServiceReference.DomainOperation.Update
            '' Send the changes back to the server as an array of ChangeSetEntries  
            'Dim updateResults = dataService.SubmitChanges(New List(Of UI.Process.ATSDataDomainServiceReference.ChangeSetEntry)() From {changeEntry})
            'Dim fetchtasks As List(Of MainAssetsTable) = dataService.MainAssetsTables_All("").RootResults
            'dataService.Close()


            'Dim updateAsset As QueryResultOfMainAssetsTable = dataService.MainAssetsTables_SingleOrDefault("", "123")
            'If Not updateAsset Is Nothing Then
            '    Dim selectedAsset As New MainAssetsTable
            '    selectedAsset = updateAsset.RootResults.First
            '    With selectedAsset
            '        .LastScanDate = Now
            '        .LastModifiedBy = "joko"
            '        .LastModified = Now
            '    End With

            '    Dim updateAssetTable As New UI.Process.ATSDataDomainServiceReference.ChangeSetEntry '= New UI.Process.ATSDataDomainServiceReference.ChangeSetEntry()
            '    With updateAssetTable
            '        .Entity = selectedAsset
            '        .Operation = UI.Process.ATSDataDomainServiceReference.DomainOperation.Update
            '    End With
            '    Dim var = dataService.SubmitChanges(New List(Of UI.Process.ATSDataDomainServiceReference.ChangeSetEntry)() From {updateAssetTable})
            'End If

        End Using










        '       Dim rfid As QueryResultOfRFIDScanHistory = proxy.RFIDScanHistories_All(DomainOperation.Query)



        '       ' Retrieve the full collection,   
        '       ' no ability to filter server side unless additional methods exposed  
        '       Dim result As QueryResultOfRFIDScanHistory = proxy.RFIDScanHistories_All(DomainOperation.Query)
        '       Dim tasks As List(Of RFIDScanHistory) = result.RootResults

        '       ' Extract the real collection from the wrapper    
        '       ' Make a modification  
        '       tasks.Add(New RFIDScanHistory())


        '(.DateScanned = Now
        '       tasks.RFIDNum = "123"
        '       ' Wrap it in ChangeSetEntry  
        '       Dim changeEntry As New ChangeSetEntry()
        '       changeEntry.Entity = tasks
        '       changeEntry.Operation = DomainOperation.Insert
        '       ' Send the changes back to the server as an array of ChangeSetEntries  
        '       proxy.SubmitChanges(New ChangeSetEntry())
        '       Dim newFetchTasks As Task() = proxy.GetTasks().RootResults
        '       proxy.Close()



        'connector.


        'Label2.Content = DateDiff(DateInterval.Second, CDate(Label1.Content), Now)
    End Sub



    Private Sub MainWindow_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded


        Label1.Content = Now.ToShortDateString
        oRapi = New RAPI
        If Not oRapi.DevicePresent Then
            connectedNo.Visibility = Windows.Visibility.Visible
            connectedYes.Visibility = Windows.Visibility.Collapsed
            panelConnectToReader.Visibility = Windows.Visibility.Visible
            panelExtractFiles.Visibility = Windows.Visibility.Hidden
        Else
            connectedNo.Visibility = Windows.Visibility.Collapsed
            connectedYes.Visibility = Windows.Visibility.Visible
            panelExtractFiles.Visibility = Windows.Visibility.Visible
            panelConnectToReader.Visibility = Windows.Visibility.Hidden

        End If

    End Sub

    Private Function IsDeviceConnected() As Boolean
        Try
            If oRapi.DevicePresent Then
                oRapi.Connect()
                If oRapi.Connected Then
                    connectedNo.Visibility = Windows.Visibility.Collapsed
                    connectedYes.Visibility = Windows.Visibility.Visible
                    Return True
                Else
                    connectedNo.Visibility = Windows.Visibility.Visible
                    connectedYes.Visibility = Windows.Visibility.Collapsed
                End If
            End If
        Catch ex As Exception
            If MsgBox("Cannot connect to the device. " & ControlChars.Lf & ControlChars.Lf & ex.Message.ToString & ControlChars.Lf & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Device not found") = MsgBoxResult.Yes Then
                Return True
            End If
            Return False
        End Try
        If MsgBox("Cannot connect to the device." & ControlChars.Lf & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Device not found") = MsgBoxResult.Yes Then
            Return True
        End If
        Return False
    End Function

    Private Function FilesFoundOnDevice() As Boolean
        Dim files As Boolean = False
        Dim di As DirectoryInfo

        Try
            remotefileCount = 0
            If Not oRapi.EnumFiles(remoteLocation & "*.txt") Is Nothing Then
                remotefileCount = oRapi.EnumFiles(remoteLocation & "*.txt").Count
            End If
            If remotefileCount > 0 Then
                Try
                    di = New DirectoryInfo(localLocation)
                    If Not di.Exists Then
                        di.Create()
                    End If
                    For int As Integer = 0 To remotefileCount - 1
                        Try
                            oRapi.CopyFileFromDevice(localLocation & oRapi.EnumFiles(remoteLocation & "*.txt").Item(int).FileName, remoteLocation & oRapi.EnumFiles(remoteLocation & "*.txt").Item(int).FileName, True)
                            files = True
                        Catch RAPIerr As RAPIException
                            If MsgBox(RAPIerr.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                                files = True
                            End If
                        Catch ex As Exception
                            If MsgBox(ex.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                                files = True
                            End If
                        End Try
                    Next
                Catch ex As Exception
                    If MsgBox(ex.ToString & remoteLocation.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                        files = True
                    End If
                End Try
            Else
                If MsgBox("No files found under reader directory " & remoteLocation.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                    files = True
                End If
            End If
        Catch RAPIerr As RAPIException
            If MsgBox(RAPIerr.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed.") = MsgBoxResult.Yes Then
                files = True
            End If
        Catch ex As Exception
            If MsgBox("No files found at reader location: " & remoteLocation.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                files = True
            End If
        Finally
        End Try
        oRapi.Disconnect()
        Return files
    End Function

    Private Sub removeFilesFromDevice()
        Try
            oRapi.Connect()
            If oRapi.Connected Then
                Dim fileCount As Integer = oRapi.EnumFiles(remoteLocation & "*.txt").Count
                For int As Integer = 0 To fileCount - 1
                    Try
                        oRapi.DeleteDeviceFile(remoteLocation & oRapi.EnumFiles(remoteLocation & "*.txt").Item(0).FileName)
                    Catch RAPIerr As RAPIException
                        MsgBox(RAPIerr.ToString, MsgBoxStyle.Information, "Failed to remove files. Reconnect device and try again")
                    End Try
                Next
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Information, "Failed to remove files. Reconnect device and try again")
        End Try
        oRapi.Disconnect()
    End Sub

    Private Sub UpdateRFIDData()
       
                    
        busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Visible


        _backgroundWorker = New BackgroundWorker
                    _backgroundWorker.RunWorkerAsync()


                    

                    


                    

               
    End Sub


    Sub processFiles()


        Dim currentRow() As String
        Dim fldCtr As Integer


        SearchCriteria = String.Empty

        Try


            CriteriaPath = path.Substring(0, path.LastIndexOf("\"))

            If SearchCriteria.Length = 0 Then
                SearchCriteria = "*.txt"
            Else
                SearchCriteria = path.Substring(path.LastIndexOf("\") + 1)
            End If

            If Directory.GetFiles(CriteriaPath, SearchCriteria).Count > 0 Then




                Using New OperationContextScope(auth.InnerChannel)
                    Dim result = auth.Login("admin", "joko123!", True, "").RootResults.FirstOrDefault()

                    ' Extract the cookie embedded in the received web service response
                    ' and stores it locally
                    'Dim response As HttpResponseMessageProperty = DirectCast(OperationContext.Current.IncomingMessageProperties(HttpResponseMessageProperty.Name), HttpResponseMessageProperty)
                    'sharedCookie = response.Headers("Set-Cookie")
                End Using

                For Each files In Directory.GetFiles(CriteriaPath, SearchCriteria)
                    fileCtr += 1

                    filename = Mid(files, localLocation.Length + 1, files.Length - localLocation.Length + 1)

                    Dim parser As New FileIO.TextFieldParser(files)
                    parser.TextFieldType = FileIO.FieldType.Delimited
                    parser.SetDelimiters(" ")
                    While Not parser.EndOfData
                        parser.ReadFields()
                    End While
                    parser.Close()
                    parser = New FileIO.TextFieldParser(files)
                    parser.TextFieldType = FileIO.FieldType.Delimited
                    parser.SetDelimiters(" ")
                    While Not parser.EndOfData
                        fldCtr = 1
                        Try
                            currentRow = parser.ReadFields()
                            Dim currentField As String
                            For Each currentField In currentRow
                                If fldCtr = 2 Then
                                    Dim rfidNumber As String = Mid(currentRow(1), currentRow(1).Length - 9, 10)
                                    Dim rfidScanDate As Date = CDate(Mid(filename, 1, 4) & "/" & Mid(filename, 5, 2) & "/" & Mid(filename, 7, 2))

                                    Using New OperationContextScope(dataService.InnerChannel)

                                        Dim checkRFIDRecord = dataService.RFIDScanHistories_SingleOrDefault("", rfidNumber, rfidScanDate)
                                        If checkRFIDRecord.RootResults.Count = 0 Then
                                            ' Embeds the extracted cookie in the next web service request
                                            ' Note that we manually have to create the request object since
                                            ' since it doesn't exist yet at this stage 

                                            Dim newScan As New ATS.UI.Process.ATSLOCALServiceReference.RFIDScanHistory
                                            With newScan
                                                .RFIDNum = rfidNumber
                                                .DateScanned = rfidScanDate
                                            End With

                                            Dim csEntry As UI.Process.ATSLOCALServiceReference.ChangeSetEntry = New UI.Process.ATSLOCALServiceReference.ChangeSetEntry()
                                            With csEntry
                                                .Operation = UI.Process.ATSLOCALServiceReference.DomainOperation.Insert
                                                .Entity = newScan
                                            End With

                                            dataService.SubmitChanges(New List(Of UI.Process.ATSLOCALServiceReference.ChangeSetEntry)() From {csEntry})


                                            Dim asset = dataService.AssetByRFIDNo("", rfidNumber)
                                            If asset.RootResults.Count > 0 Then


                                                Dim mAssetorig As New UI.Process.ATSLOCALServiceReference.MainAssetsTable
                                                With asset.RootResults.FirstOrDefault
                                                    mAssetorig.AssetAmount = .AssetAmount
                                                    mAssetorig.Assetno = .Assetno
                                                    mAssetorig.AssignToEmployeeCode = .AssignToEmployeeCode
                                                    mAssetorig.BaseCost = .BaseCost
                                                    mAssetorig.BoughtFrom = .BoughtFrom
                                                    mAssetorig.BrandName = .BrandName
                                                    mAssetorig.CategoryCode = .CategoryCode
                                                    mAssetorig.Condition = .Condition
                                                    mAssetorig.Createdby = .Createdby
                                                    mAssetorig.DateAcquired = .DateAcquired
                                                    mAssetorig.DateCreated = .DateCreated
                                                    mAssetorig.DeptCode = .DeptCode
                                                    mAssetorig.DescriptiveName = .DescriptiveName
                                                    mAssetorig.EstimatedValue = .EstimatedValue
                                                    mAssetorig.InvoiceNumber = .InvoiceNumber
                                                    mAssetorig.LastModified = .LastModified
                                                    mAssetorig.LastModifiedBy = .LastModifiedBy
                                                    mAssetorig.LastScanDate = .LastScanDate
                                                    mAssetorig.LocationCode = .LocationCode
                                                    mAssetorig.Manufacturer = .Manufacturer
                                                    mAssetorig.ModelNumber = .ModelNumber
                                                    mAssetorig.Remarks = .Remarks
                                                    mAssetorig.ReplacementCost = .ReplacementCost
                                                    mAssetorig.RFIDno = .RFIDno
                                                    mAssetorig.SalvageValue = .SalvageValue
                                                    mAssetorig.Section = .Section
                                                    mAssetorig.SerialNumber = .SerialNumber
                                                    mAssetorig.Status = .Status
                                                    mAssetorig.VAT = .VAT
                                                End With
                                                'mAssetorig.id = asset.RootResults.FirstOrDefault.id
                                                'mAssetorig.c_property = asset.RootResults.FirstOrDefault.c_property
                                                'mAssetorig.value = asset.RootResults.FirstOrDefault.value
                                                asset.RootResults.FirstOrDefault.LastModified = Now
                                                asset.RootResults.FirstOrDefault.LastModifiedBy = "me"
                                                asset.RootResults.FirstOrDefault.LastScanDate = rfidScanDate

                                                csEntry = New UI.Process.ATSLOCALServiceReference.ChangeSetEntry
                                                With csEntry
                                                    .Operation = UI.Process.ATSDataDomainServiceReference.DomainOperation.Update
                                                    .OriginalEntity = mAssetorig
                                                    .Entity = asset.RootResults.FirstOrDefault
                                                End With


                                                dataService.SubmitChanges(New List(Of UI.Process.ATSLOCALServiceReference.ChangeSetEntry)() From {csEntry})
                                            Else
                                                notRelatedToAnyAsset += 1

                                            End If
                                        Else
                                            duplicatesCtr += 1

                                        End If
                                    End Using

                                    'Label2.Content = DateDiff(DateInterval.Second, CDate(Label1.Content), Now)



                                End If
                                fldCtr += 1
                            Next
                        Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                            MsgBox("Line " & ex.Message & _
                            "is not valid and will be skipped.")
                        End Try
                    End While
                    parser.Close()
                    FileFound += 1
                    If File.Exists(files) Then
                        File.Move(files, Mid(files, 1, files.Length - 3) & Format(Now(), "ddMMyyhhmmss"))
                    Else
                        File.Move(files, Mid(files, 1, files.Length - 3) & "old")
                    End If
                Next
            Else
                Throw New Exception("No reader files exists at " & CriteriaPath)
            End If

        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub
    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonProcessReaderFiles.Click
        If IsDeviceConnected() Then

            If oRapi IsNot Nothing Then

                If FilesFoundOnDevice() Then
                    If remotefileCount > 0 Then

                        If retainFilesonReader Then
                            removeFilesFromDevice()
                        End If

                    End If

                    UpdateRFIDData()

                End If

            Else

                UpdateRFIDData()
            End If

        End If

    End Sub

    Private Sub ButtonConnectToReader_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles ButtonConnectToReader.Click
        If oRapi.DevicePresent Then
            oRapi.Connect()
            If oRapi.Connected Then
                connectedNo.Visibility = Windows.Visibility.Collapsed
                connectedYes.Visibility = Windows.Visibility.Visible
                panelExtractFiles.Visibility = Windows.Visibility.Visible
                panelConnectToReader.Visibility = Windows.Visibility.Hidden
            Else
                connectedNo.Visibility = Windows.Visibility.Visible
                connectedYes.Visibility = Windows.Visibility.Collapsed
                panelConnectToReader.Visibility = Windows.Visibility.Visible
                panelExtractFiles.Visibility = Windows.Visibility.Hidden
            End If
        End If
    End Sub


    
End Class

